﻿/*
 * NetworkHelper
 * 
 * Author: snowdreamist
 * Date: 2011/11/20
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitTorrentSharp.Helpers
{
    public static class NetworkHelper
    {
        /// <summary>
        /// Convert
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string ConvertIPv4BytesToString(byte[] ip, bool isNetworkOrder = true)
        {
            if (ip == null)
                throw new ArgumentNullException("ip");
            if (ip.Length != 4)
                throw new ArgumentException("ip's length should be 4");

            UInt32 value = 0;

            if (isNetworkOrder)
                value = ip.ConvertToUInt32WithBigEnding();
            else
                value = ip.ConvertToUInt32WithLittleEnding();

            // conver to string
            return string.Format("{0}.{1}.{2}.{3}",
                ((value & 0xff000000) >> 24),
                ((value & 0x00ff0000) >> 16),
                ((value & 0x0000ff00) >> 8),
                ((value & 0x000000ff))
                );
        }
        /// <summary>
        /// Convert
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public static int ConvertPortBytesToInt(byte[] port, bool isNetworkOrder = true)
        {
            if (port == null)
                throw new ArgumentNullException("port");
            if (port.Length > 2)
                throw new ArgumentException("port's max length should be smaller than 3");
            if (port.Length == 0)
                return 0;
            else if (port.Length == 1)
                return (int)port[0];
            else
            {
                if (isNetworkOrder)
                {
                    // big ending
                    return (int)port.ConvertToUInt32WithBigEnding();
                }
                else
                {
                    // little ending
                    return (int)port.ConvertToUInt32WithLittleEnding();
                }
            }
        }
    }
}
